Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

429
Views
How to remove parentheses and replace "white space" with "-" in php using preg_replace

This is What I Have - Huawei MatePad 11 (2021)

This is what I want - Huawei-MatePad-11-2021

This is what I have done so far. (only it replaces "white space" with "-".

echo preg_replace('/[[:space:]]+/', '-', $test);

I want to remove parentheses, and want to replace "white space" with "-" at once. How to do it?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

$text = 'Huawei MatePad 11 (2021)';
$text = preg_replace('/[(|)]/', '', preg_replace('/\s+/', '-', $text));

echo($text);
over 4 years ago · Santiago Trujillo Report

0

$test = preg_replace('/[[:space:]]+/', '-', $test); # Replace space
$test = preg_replace('/[\(|\)]+/', '', $test);      # Replace parenthesis 

echo $test;
over 4 years ago · Santiago Trujillo Report

0

You might also use a single pattern with preg_replace_callback and match from an opening till closing parenthesis.

\(([^()]+)\)|\h+

The pattern matches:

  • \( Match (
  • ([^()]+) Capture group 1 match 1+ chars other than ( )
  • \) Match )
  • | Or
  • \h+ Match 1 or more horizontal whitespace chars

Php demo | Regex demo

For example return group 1 using $m[1] if it exists, else return -

$s = "Huawei MatePad 11 (2021)";
$regex = "/\(([^()]+)\)|\h+/";
$result = preg_replace_callback($regex, function($m) {
    return array_key_exists(1, $m) ? $m[1] : '-';
}, $s);
echo $result;

Output

Huawei-MatePad-11-2021
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!